package models

import (
	"cloud-disk/core/internal/config"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"os"

	//"gorm.io/gorm/logger"
	"log"
	//"os"
	"time"
)

func InitDB(config config.Config) *gorm.DB {
	log.Println("initDB start...")
	//自定义日志模版 打印sql语句
	slowLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold: time.Millisecond, //慢sql阈值
			LogLevel:      logger.Info,
			Colorful:      true,
		},
	)
	Conn, err := gorm.Open(mysql.Open(config.Mysql.DNS), &gorm.Config{Logger: slowLogger})
	//Conn, err := gorm.Open(mysql.Open(config.Mysql.DNS))
	if err != nil {
		log.Println("initDB open err:", err)
	}
	sqlDB, _ := Conn.DB()
	sqlDB.SetMaxIdleConns(50)
	sqlDB.SetMaxOpenConns(300)
	sqlDB.SetConnMaxIdleTime(10 * time.Minute)
	sqlDB.SetConnMaxLifetime(60 * time.Minute)
	return Conn
}
